package cn.donghuapian.component;

import com.baomidou.mybatisplus.core.toolkit.AES;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @description: 读取，修改yml文件内容，参考SafetyEncryptProcessor
 * @author: hzw
 * @time: 2024/10/28 16:31
 */
public class DynamicEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        MutablePropertySources propertySources = environment.getPropertySources();
        Iterator<PropertySource<?>> iterator = propertySources.iterator();
        while(iterator.hasNext()) {
            PropertySource propertySource = iterator.next();
            //不是
            if(!(propertySource instanceof OriginTrackedMapPropertySource)) {
                continue;
            }
            OriginTrackedMapPropertySource source = (OriginTrackedMapPropertySource)propertySource;
            Map<String, Object> map = source.getSource();
            Object flag = map.get("donghuapian.encrypt");
            if(null == flag || !"true".equals(flag.toString())) {
                break;
            }
            Map<String, Object> newMap = new HashMap<>(map);

            String[] propertyNames = source.getPropertyNames();
            for(int i = 0; i < propertyNames.length; i++) {
                String name = propertyNames[i];
                Object value = source.getProperty(name);
                if (value instanceof String) {
                    String valueStr = (String)value;
                    //这里可以改变yml中的值
                    if(valueStr.equals("spring.datasource.password")) {
                        newMap.put(name, value);
                    }
                }
            }
            String propertySourceName = propertySource.getName();
            OriginTrackedMapPropertySource newSource = new OriginTrackedMapPropertySource(propertySourceName, newMap);
            propertySources.replace(propertySourceName, newSource);

        }
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
